﻿/**
 * @Create time : 2014年9月12日19:08:12
 * @Update time : 2014年9月14日22:20:04
 * @Author : magicrolan
 **/

using UnityEngine;
using CommandHandler;
using System;
using System.Timers;
using System.IO;
using Ini;
using System.Net;
using System.Text;

namespace OnlinePlayers
{
    //Make the classname unique so it doesn't interfere with other mods
    // Keep the MonoBehaviour though
    public class OnlinePlayers : MonoBehaviour
    {
        public int refreshDelayInSeconds = 60;
        public int configSize = 2;
        public static string getSteam64ID = "true";
        public static string playerXYZ = "true";
        public static string jsondata = "";
        // public string checkactionurl = "http://localhost/unturnedapis/actions/?port=25444&action=ban&player=magicrolan,alex,liasica";
        public Timer resfreshTimer;

        // Json data
        public static string Getjson(string action)
        {
            string getWeatherUrl = "http://localhost/unturnedapis/actions/?action=" + action;
            WebRequest webReq = WebRequest.Create(getWeatherUrl);
            WebResponse webResp = webReq.GetResponse();
            Stream stream = webResp.GetResponseStream();
            StreamReader sr = new StreamReader(stream, Encoding.UTF8);
            string html = sr.ReadToEnd();
            sr.Close();
            stream.Close();
            return html;
        }


        public static void OutputTxtLine(string p) // 将字符串写入文件
        {
            StreamWriter writer = new StreamWriter("Unturned_Data/Managed/mods/OnlinePlayers/OnlinePlayers.txt", true);
            writer.WriteLine(p); // 每行一个
            writer.Close();
        }

        public static void OutputTxtInline(string p)
        {
            StreamWriter writer = new StreamWriter("Unturned_Data/Managed/mods/OnlinePlayers/OnlinePlayers.txt", true);
            writer.Write(p); // 同一行
            writer.Close();
        }

        private void GetOnlinePlayers(CommandArgs args) // 指令
        {
            OutputPlayers();
            Reference.Tell(args.sender.networkPlayer, "Exported");
        }


        public static string GetTimeStamp() // 时间戳
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        public static void OutputPlayers() // 输出玩家
        {
            //DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            jsondata = "{\"time\":" + GetTimeStamp() + ",\"onlineplayers\":[";
            foreach (BetterNetworkUser user in UserList.users)
            {
                jsondata += "[\"" + user.name + "\"";
                string jsondataend = ",";
                if (UserList.users.IndexOf(user) + 1 == UserList.NetworkUsers.Count)
                {
                    jsondataend = "";
                }
                if (getSteam64ID == "true")
                {
                    jsondata += ",\"" + user.steamid + "\"";
                }
                if (playerXYZ == "true")
                {
                    Vector3 playerPosition = user.position;
                    float x = playerPosition[0];
                    float y = playerPosition[1];
                    float z = playerPosition[2];
                    jsondata += ",\"" + x + "," + y + "," + z + "\""; 
                }
                jsondata += "]" + jsondataend;
            }
            jsondata += "]}";
            OutputTxtLine(jsondata);  // output
            string s = Getjson("ban");
            OutputTxtLine(s);
        }

        public void writeIniFile()
        {
            IniFile configFile = new IniFile("Unturned_Data/Managed/mods/OnlinePlayers/config.ini");
            configFile.IniWriteValue("Timer", "Refresh online players", "60"); // Default 60000 milliseconds = 1 mintue
            configFile.IniWriteValue("Config", "Log txt file maxsize", "2"); // Log txt file maxsize 1024Bytes = 1Mb
            configFile.IniWriteValue("Config", "Log player's steam64 ID", "true"); // true false
            configFile.IniWriteValue("Config", "Log player's coordinate", "true"); // true false
        }

        public void onStart() // 开始函数
        {
            Directory.CreateDirectory("Unturned_Data/Managed/mods/OnlinePlayers"); // 生成配置目录
            if (!File.Exists("Unturned_Data/Managed/mods/OnlinePlayers/OnlinePlayers.txt")) // 生成记录
            {
                OutputTxtInline("");
            }

            if (!File.Exists("Unturned_Data/Managed/mods/OnlinePlayers/config.ini"))
            {
                writeIniFile();
            }


            IniFile configfile = new IniFile("Unturned_Data/Managed/mods/OnlinePlayers/config.ini");

            // 检查配置文档
            if (configfile.IniReadValue("Timer", "Refresh online players").Length > 0)
            {
                this.refreshDelayInSeconds = Convert.ToInt32(configfile.IniReadValue("Timer", "Refresh online players"));
            }
            if (configfile.IniReadValue("Config", "Log txt file maxsize").Length > 0)
            {
                this.configSize = Convert.ToInt32(configfile.IniReadValue("Config", "Log txt file maxsize"));
            }
            if (configfile.IniReadValue("Config", "Log player's steam64 ID").Length > 0)
            {
                getSteam64ID = configfile.IniReadValue("Config", "Log player's steam64 ID");
            }
            if (configfile.IniReadValue("Config", "Log player's coordinate").Length > 0)
            {
                playerXYZ = configfile.IniReadValue("Config", "Log player's coordinate");
            }

            // 自动删除文件
            FileInfo Logfile = new FileInfo("Unturned_Data/Managed/mods/OnlinePlayers/OnlinePlayers.txt");
            // Logfile.Length.ToString();
            if (Logfile.Length >= (double)(this.configSize * 10000))
            {
                File.Delete("Unturned_Data/Managed/mods/OnlinePlayers/OnlinePlayers.txt");
                OutputPlayers(); // 重新生成
            }

            // 定时器
            this.resfreshTimer = new System.Timers.Timer((double)(this.refreshDelayInSeconds * 0x3e8));
            this.resfreshTimer.Elapsed += new ElapsedEventHandler(this.GetOnline);
            this.resfreshTimer.Enabled = true;

        }

        private void GetOnline(object sender, ElapsedEventArgs e)
        {
            OutputPlayers();
        }







        public void Start() //Will be called when this mod is loaded
        {
            onStart();
            CommandList.add(new Command(GetOnlinePlayers, "getplayers"));
        }

        public void Update()  //Will be called once per frame update
        {

        }

        public void OnGui()  //Will be called multiple times per frame update
        {

        }

    }
}
